
#include "Config.hpp"
#include <iostream>
#include <sstream>
#include <stdexcept>

Config* Config::s_instance = 0;

Config* Config::instance()
{
  if ( ! s_instance )
    s_instance = new Config;
  return s_instance;
}

void
Config::read ( const string& p_file )
{
  ifstream config(p_file.c_str());
  if ( config.fail() )
    throw ( runtime_error ("Config file open failed"));
  
  string line, key;
  // get the key
  while ( config >> key )
    {
      // read the rest of the line
      getline (config,line);
      // ignore comments
      if ( key[0] == '#' )
	continue;

      string cLine;
      int pos;
      if ( ( pos = line.find_last_not_of(" \t\r") ) > 0 && line[pos] == '\\' )
	{
	  cLine = line.substr(0,pos);
	  getline (config,line);
	  while ( ( pos = line.find_last_not_of(' ') ) > 0 && line[pos] == '\\' )
	    {
	      cLine += line.substr(0,pos);
	      getline (config,line);
	    }
	  cLine += line;
	}
      else
	cLine = line;

      istringstream istr ( cLine );
      string tmp, value;
      while ( istr >> tmp )
	{
	  if ( ! value.size() )
	    value = tmp;
	  else
	    value += " " + tmp;
	}
      m_keyValMap.insert(pair<string,string>(key,value));
      //cout << "key: " << key << ", value: " << value << endl;
    }
  config.close();
  iter = m_keyValMap.begin();
}

pair < string, vector<double> > Config::element()
{
  string name = iter->first;
  string value = iter->second;
  vector<double> dvec;
  istringstream istr ( value );
  double tmp;
  while ( istr >> tmp )
    dvec.push_back(tmp);
  ++iter;
  return pair < string, vector<double> > (name,dvec);
}

bool
Config::next() const
{
  return iter != m_keyValMap.end();
}
